import pickle
import os

class ConfigManager:
    def __init__(self, config_file = 'config.pkl'):
        self.config_file = config_file
        self.load()


    def get(self, key, default_value=None):
        if key not in self.data:
            self.set(key, default_value)
        return self.data[key]


    def set(self, key, value):
        self.data[key] = value
        self.dirty = True


    def load(self):
        if os.path.exists(self.config_file):
            with open(self.config_file, 'rb') as file:
                self.data = pickle.load(file)
        else:
            self.data = {}
        self.dirty = False


    def save(self):
        if self.dirty:
            with open(self.config_file, 'wb') as file:
                pickle.dump(self.data, file)
            self.dirty = False


if __name__ == '__main__':
    file_path = 'config2.pkl'
    if os.path.exists(file_path): # 删除文件
        os.remove(file_path)
        print(f"文件 '{file_path}' 已被删除。")
    else:
        print(f"文件 '{file_path}' 不存在。")
    config = ConfigManager(file_path)
    config.set('name', 'Alice')
    config.save()

    config.load()
    print(config.get('name'))  # 输出: Alice
    print(config.get('age', 30))  # 输出: 30
